<?php

namespace App\Listeners;

use App\Events\GameFinish;
use App\Models\Admin;
use App\Models\ChildNotices;
use App\Models\ChildStar;
use App\Models\History;
use App\Models\Notice;
use App\Models\Role;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use function AlibabaCloud\Client\json;

class SendNotice
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  GameFinish  $event
     * @return void
     */
    public function handle(GameFinish $event)
    {
        $tmp = $event->history;

        if (config("site.other.is_overtime") == 1){
            $child = $tmp->child;
            Log::error("zzz");
            Log::error(json_encode($child));
            if (empty($child)){
                Log::error("child is empty");
                return;
            }

            $notices = $child->notices();
            Log::error(json_encode($notices));

            //if (ChildNotices::where('child_id', $tmp->child_id)->where('created_at', '>', date('Y-m-d'))->exists()){
            if (Notice::where('created_at', '>', date('Y-m-d'))->whereHas('childNotice', function ($item) use ($tmp){
                    $item->where("child_id", $tmp->child_id);
                })->exists()){
                Log::error("ChildNotice today is exit");
            }else{
                $overtime = config("site.other.overtime_time");
                $play_time = History::where('child_id', $tmp->child_id)->where('created_at', '>', date("Y-m-d"))->sum("use_time");
                if ($play_time > $overtime*60){
                    DB::transaction(function() use ($tmp, $overtime){
                        Log::error("tmp");
                        Log::error($tmp);

                        $title = sprintf("%s 训练超过设定值", $tmp->agency->name);

                        $content = sprintf("%s 学生:%s 训练超过设定值（%u分钟）（<a href='%s'>查看</a>） ", $tmp->agency->name,
                            $tmp->child->name,$overtime,route("admin.training.index", ['child_id'=>$tmp->child_id]));

                        $data = ['title'=>$title, 'content'=>$content,'type'=>Notice::TYPE_SAFE];
                        $notice = Notice::create($data);

                        //$notice->child->attach($tmp->child_id);
                        $notice->childNotice()->create(['child_id'=>$tmp->child_id]);

                        $role = Role::find(1);
                        $observer = $role->adminRoles()->pluck('admin_id')->toArray();
                        $notice->admins()->attach($observer);
                    },5);
                }else{
                    Log::error("not over time");
                }
                Log::error("ChildNotice today is send");
            }
        }else{
            Log::error("is not overtime");
        }
    }
}
